package cn.tedu.order.service;
import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.tcc.OrderTccAction;
import io.seata.rm.tcc.api.BusinessActionContext;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Random;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private StorageClient storageClient;
    @Autowired
    private OrderTccAction tcc;

    @GlobalTransactional //第一个模块上，启动全局事务
    @Override
    public void create(Order order) {
        // 远程调用全局唯一id发号器，获得订单id
        Map<String, String> map =
                easyIdClient.nextId("order_business");
        String s = map.get("data");
        long orderId = Long.valueOf(s);

        order.setId(orderId);

        // orderMapper.create(order); //创建正常的订单

        // 调用第一阶段方法，冻结订单
        /*
        tcc对象是 AOP 创建的动态代理对象，
        通过 AOP 的“通知”添加了前置代码，会创建上下文对象传入原始的方法
         */
        tcc.prepare(null,
                order.getId(),
                order.getUserId(),
                order.getProductId(),
                order.getCount(),
                order.getMoney());


        // 远程调用库存，减少库存
        storageClient.decrease(order.getProductId(), order.getCount());
        // 远程调用账户，扣减金额
        accountClient.decrease(order.getUserId(),order.getMoney());

    }
}
